package cn.hchaojie.camp.day09;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import org.junit.Test;

// checked exception ：受检异常。编译的时候，编译器会强制你处理

// 1. 要么在当前的方法里面try catch
// 2. 要么你往上面抛，让调用的人去处理

// RuntimeException: 运行的时候才出现
public class DemoCheckedException {
	public static void main(String[] args) {
		File file = new File("d:\\test.java");
		
		try {
			file.createNewFile();
			
			System.out.println("创建文件成功！");
		} catch (IOException e) {
			System.out.println("创建文件失败！");
			e.printStackTrace();
		}
		
		System.out.println("异常处理完毕");
	}
	
	/**
	 * 文件读取，演示受检异常的处理流程
	 * @throws IOException 
	 */
	@Test
	public void testFileRead() {
		FileReader reader = null;
		try {
			 reader = new FileReader("D:\\camp\\camp2018\\code\\src\\cn\\hchaojie\\camp\\day07\\Employee1.java");
			
			char[] chars = new char[10];
			int count = reader.read(chars);
			
			System.out.println(new String(chars));
			
		} catch (Exception e) {		
			e.printStackTrace();	// 
		} finally {
			// 清理资源
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			System.out.println("finally...");
		}
	}
	
	@Test
	public void testFileRead2() {
		String file = "D:\\camp\\camp2018\\code\\src\\cn\\hchaojie\\camp\\day07\\Employee1.java";
		try (FileReader reader = new FileReader(file)) {
			
			char[] chars = new char[10];
			int count = reader.read(chars);
			
			System.out.println(new String(chars));
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();	// 
		} catch (IOException e) {
			e.printStackTrace();
		} 
		// 不需要在finally里面清理资源， java7 
	}
	
	@Test
	public void testFileRead3() throws FileNotFoundException, IOException {
		String file = "D:\\camp\\camp2018\\code\\src\\cn\\hchaojie\\camp\\day07\\Employee1.java";
		FileReader reader = new FileReader(file);
			
		char[] chars = new char[10];
		int count = reader.read(chars);
		
		System.out.println(new String(chars));
	}
	
	@Test
	public void test() throws IOException {
		testFileRead3();
	}
	
	// 文件读取
	@Test
	public void test2() {
		String file = "D:\\camp\\camp2018\\code\\src\\cn\\hchaojie\\camp\\day07\\Employee.java";

		List<String> lines = null;
		try {
			lines = Files.readAllLines(Paths.get(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if (lines == null) return;

		for (String line : lines) {
			System.out.println(line);
		}
	}
}
